#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
颜色高亮工具
提供终端文本颜色和样式功能
"""

import re
import sys


class Colors:
    """ANSI颜色代码常量"""
    # 重置
    RESET = '\033[0m'
    
    # 基本颜色
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    
    # 亮色
    BRIGHT_BLACK = '\033[90m'
    BRIGHT_RED = '\033[91m'
    BRIGHT_GREEN = '\033[92m'
    BRIGHT_YELLOW = '\033[93m'
    BRIGHT_BLUE = '\033[94m'
    BRIGHT_MAGENTA = '\033[95m'
    BRIGHT_CYAN = '\033[96m'
    BRIGHT_WHITE = '\033[97m'
    
    # 样式
    BOLD = '\033[1m'
    DIM = '\033[2m'
    ITALIC = '\033[3m'
    UNDERLINE = '\033[4m'
    BLINK = '\033[5m'
    REVERSE = '\033[7m'
    STRIKETHROUGH = '\033[9m'
    
    # 背景色
    BG_BLACK = '\033[40m'
    BG_RED = '\033[41m'
    BG_GREEN = '\033[42m'
    BG_YELLOW = '\033[43m'
    BG_BLUE = '\033[44m'
    BG_MAGENTA = '\033[45m'
    BG_CYAN = '\033[46m'
    BG_WHITE = '\033[47m'


def is_terminal_supports_color():
    """检查终端是否支持颜色"""
    return hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()


def highlight_text(text, style='red_bold'):
    """
    高亮文本
    
    Args:
        text: 要高亮的文本
        style: 高亮样式
        
    Returns:
        str: 高亮后的文本
    """
    if not is_terminal_supports_color():
        return f"[{text}]"  # 如果不支持颜色，使用方括号
    
    styles = {
        'red_bold': f"{Colors.BOLD}{Colors.RED}",
        'green_bold': f"{Colors.BOLD}{Colors.GREEN}",
        'yellow_bold': f"{Colors.BOLD}{Colors.YELLOW}",
        'blue_bold': f"{Colors.BOLD}{Colors.BLUE}",
        'cyan_bold': f"{Colors.BOLD}{Colors.CYAN}",
        'magenta_bold': f"{Colors.BOLD}{Colors.MAGENTA}",
        'red_bg': f"{Colors.BG_RED}{Colors.WHITE}",
        'yellow_bg': f"{Colors.BG_YELLOW}{Colors.BLACK}",
        'green_bg': f"{Colors.BG_GREEN}{Colors.BLACK}",
        'underline': f"{Colors.UNDERLINE}",
        'bright_red': f"{Colors.BRIGHT_RED}",
        'bright_green': f"{Colors.BRIGHT_GREEN}",
        'bright_yellow': f"{Colors.BRIGHT_YELLOW}",
    }
    
    color_code = styles.get(style, styles['red_bold'])
    return f"{color_code}{text}{Colors.RESET}"


def process_highlight_fragment(fragment, highlight_style='red_bold'):
    """
    处理搜索结果片段中的高亮标记
    
    Args:
        fragment: 包含高亮标记的文本片段
        highlight_style: 高亮样式
        
    Returns:
        str: 处理后的文本
    """
    # 处理自定义高亮标记
    fragment = re.sub(r'<HIGHLIGHT>(.*?)</HIGHLIGHT>', 
                     lambda m: highlight_text(m.group(1), highlight_style), 
                     fragment)
    
    # 处理其他可能的HTML标记
    fragment = re.sub(r'<em>(.*?)</em>', 
                     lambda m: highlight_text(m.group(1), 'yellow_bold'), 
                     fragment)
    
    fragment = re.sub(r'<mark>(.*?)</mark>', 
                     lambda m: highlight_text(m.group(1), 'green_bold'), 
                     fragment)
    
    return fragment


def print_colored(text, color='white', style=None):
    """
    打印彩色文本
    
    Args:
        text: 要打印的文本
        color: 颜色名称
        style: 样式（bold, underline等）
    """
    if not is_terminal_supports_color():
        print(text)
        return
    
    color_map = {
        'black': Colors.BLACK,
        'red': Colors.RED,
        'green': Colors.GREEN,
        'yellow': Colors.YELLOW,
        'blue': Colors.BLUE,
        'magenta': Colors.MAGENTA,
        'cyan': Colors.CYAN,
        'white': Colors.WHITE,
        'bright_red': Colors.BRIGHT_RED,
        'bright_green': Colors.BRIGHT_GREEN,
        'bright_yellow': Colors.BRIGHT_YELLOW,
        'bright_blue': Colors.BRIGHT_BLUE,
        'bright_cyan': Colors.BRIGHT_CYAN,
    }
    
    style_map = {
        'bold': Colors.BOLD,
        'dim': Colors.DIM,
        'italic': Colors.ITALIC,
        'underline': Colors.UNDERLINE,
    }
    
    color_code = color_map.get(color, Colors.WHITE)
    style_code = style_map.get(style, '') if style else ''
    
    print(f"{style_code}{color_code}{text}{Colors.RESET}")


def demo_colors():
    """演示颜色效果"""
    print("🎨 颜色高亮效果演示:")
    print("="*50)
    
    styles = [
        ('red_bold', '红色加粗'),
        ('green_bold', '绿色加粗'),
        ('yellow_bold', '黄色加粗'),
        ('blue_bold', '蓝色加粗'),
        ('cyan_bold', '青色加粗'),
        ('red_bg', '红色背景'),
        ('yellow_bg', '黄色背景'),
        ('underline', '下划线'),
        ('bright_red', '亮红色'),
        ('bright_green', '亮绿色'),
    ]
    
    for style, description in styles:
        highlighted = highlight_text("高亮文本", style)
        print(f"{description}: 这是{highlighted}的示例")
    
    print("\n📝 搜索结果高亮示例:")
    sample_fragment = "雇主责任<HIGHLIGHT>保险</HIGHLIGHT>是一种重要的<HIGHLIGHT>风险</HIGHLIGHT>管理工具"
    processed = process_highlight_fragment(sample_fragment)
    print(f"   {processed}")


if __name__ == "__main__":
    demo_colors()